<template>
  <div style="height:100%;width:100%;position:relative;">
      <div class="pagetop" ref="buttondiv">
          <template>
              <table width="100%">
                  <tr>
                      <td style="width:40px;">仪器</td>
                      <td>
                          <rm-ddl-instrument @change="labinstrumentchange" width="200px" v-model="instrId" defaultflag="1" prgno="LIS516" :clearable="false"  ></rm-ddl-instrument>
                      </td>
                      <td style="width:40px;">对应批号</td>
                      <td style="width:150px;">
                          <el-input v-model="selbatch"  placeholder="批号"  @change="initialList" width="150px"></el-input>
                      </td>
                      <td align="right">
                          <el-button icon="el-icon-search" @click="initialList" v-has="'PINQUERY'">查询(F8)</el-button>
                          <el-button icon="el-icon-edit-outline" @click.shift="BtnAdd()" @click="BtnAdd()" v-has="'PADD'">新增(F2)</el-button>
                          <el-button icon="el-icon-delete-solid" @click="BtnDel()" v-has="'PDELETE'">删除(F3)</el-button>
                          <el-button type="primary" icon="el-icon-success" @click="BtnSave()" v-has="'PMODIFY'">保存(F6)</el-button>
                          <el-button icon="el-icon-close" @click="BtnExc">退出(E)</el-button>
                      </td>
                  </tr>
              </table>
          </template>
      </div>
      <div class="pagecenter">
          <rm-layout-right splitcolor="#FFFFFF" movingcolor="#CCFFFF" :splitwidth=5 :fixsize=450 :minfixsize="450" :maxfixsize="450" :canDrag="true">
              <div ref="xTableDiv" style="height:99%;width:100%">
                  <vxe-table show-overflow ref="xTable1" height="auto" width="100%" :loading="loading" :select-config="{ reserve: true }" :data.sync="tableData1" border size="mini" :keyboard-config="keyConfig" :mouse-config="{ selected: true }" show-header-overflow highlight-current-row highlight-hover-row resizable stripe :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @current-change="CurrentChangeEvent">
                      <vxe-table-column type="index" title="NO." width="40"></vxe-table-column>
                      <vxe-table-column field="instrsampleno" title="普通标本号" width="120px" header-align="center" :edit-render="{name:'input'}">
                      </vxe-table-column>
                      <vxe-table-column field="qclevel" title="对应质控水平" width="90" align="center">
                          <template v-slot="{ row }">
                              <rm-ddl-common datatype="seccode" kindno="QCLEVEL" dataname="水平" v-model="row.qclevel" width="110px"></rm-ddl-common>
                          </template>
                      </vxe-table-column>
                      <vxe-table-column field="batchno" title="对应批号（为空匹配最后启用的批号）" width="240" align="center" :edit-render="{name:'input' ,events: {change:batchno_changeEvent}   }"></vxe-table-column>
                      <vxe-table-column field="barcode" title="固定条码号" width="100" align="center" :edit-render="{name:'input' ,events: {change:batchno_changeEvent}   }"></vxe-table-column>
                      <vxe-table-column field="rpt_itemcodes" title="包含的报告项目" width="250" align="center"> <template v-slot="{row}">
                              <el-input v-model="row.rpt_itemcodes" @dblclick.native="addRecord" readonly></el-input>
                          </template></vxe-table-column>
                  </vxe-table>
              </div>
              <template v-slot:fix>
                  <div style="height:100%;width:100%">
                      <div class="tabtop">
                          <div class="tab-title">当前仪器质控项目</div>
                      </div>
                      <div class="datacenter">
                          <vxe-table show-overflow ref="xTable2" height="auto" width="100%" :select-config="{ reserve: true }" :data.sync="rptTableData" border size="mini" :keyboard-config="keyConfig" :mouse-config="{ selected: true }" show-header-overflow highlight-current-row highlight-hover-row resizable stripe>
                              <vxe-table-column type="index" title="NO." width="30"></vxe-table-column>
                              <vxe-table-column field="cp_selection" title="包含" width="40px" align="center">
                                  <template v-slot="{ row, rowIndex }">
                                      <el-checkbox v-model="row.sel" true-label="1" false-label="0" readonly :disabled="true"></el-checkbox>
                                  </template>
                              </vxe-table-column>
                              <vxe-table-column field="itemcode_en" title="英文缩写" width="80px" header-align="center"></vxe-table-column>
                              <vxe-table-column field="rpt_itemname" title="报告项目名称" width="120px" header-align="center">
                              </vxe-table-column>
                              <vxe-table-column field="rpt_itemcode" title="报告项目代码" width="110px" header-align="center">
                              </vxe-table-column>
                          </vxe-table>
                      </div>
                  </div>
              </template>
          </rm-layout-right>
      </div>
      <el-dialog width="1000px" top="10px" v-el-drag-dialog :append-to-body="true" destroy-on-close :close-on-click-modal="false" title="选择仪器质控项目" :visible.sync="dialogTableVisible">
          <rm-pop-selrptitem @cancel="dialogTableVisible=false;"  :instrid="instrIdItemList" @selitem="addrptitem"></rm-pop-selrptitem>
      </el-dialog>
  </div>
</template>

<script type="text/javascript">
import XEUtils from "xe-utils"; //引入工具类
export default {
  name: "LIS516",
  data() {
      return {
          loading: false,
          instrId: 0,
          tableData1: [],
          rptTableData: [],
          selbatch: "",
          keyConfig: {
              isArrow: true,
              isDel: true,
              isTab: true,
              isEdit: true,
              editMethod: ({ seq, row, rowIndex, column, columnIndex, cell }) => {},
          },
          //仪器对应项目组件
          instrIdItemList: 0,
          dialogTableVisible: false,
      };
  },

  //html加载完成之前，执行。执行顺序：父组件-子组件
  created() {},
  //.html加载完成后执行。执行顺序：子组件-父组件
  mounted() {},
  updated() {},
  watch: {
      instrId(val) {
          this.initialList();
      },
  },
  methods: {
      async CurrentChangeEvent({ row }) {
          // await this.selquery(row);
          this.chkindex();
      },
      addRecord(e) {
          //弹出新增框
          if (this.instrId == 0) {
              this.$message("请选择仪器");
              return false;
          }
          // shift 被按下
          if (e.shiftKey) {
              this.instrIdItemList = 0; //列出全部itemcode
          } else {
              this.instrIdItemList = XEUtils.toInteger(this.instrId); //列出本仪器的项目
          }
          this.dialogTableVisible = true;
      },
      addrptitem(rptitemcodeinfos) {
          var seq = 0;
          var seqk = 0;
          var ishave = false;
          var currentrow = this.$refs.xTable1.getCurrentRow();
          currentrow.rpt_itemcodes = "";
          if (currentrow) {
              for (var i = 0; i < rptitemcodeinfos.length; i++) {
                  currentrow.rpt_itemcodes += rptitemcodeinfos[i].rpt_itemcode + ",";
              }
              if (currentrow.rpt_itemcodes != "") currentrow.rpt_itemcodes = currentrow.rpt_itemcodes.substring(0, currentrow.rpt_itemcodes.length - 1);
          }
          this.chkindex();
          this.dialogTableVisible = false;
      },
      //初始化数据
      resetData() {
          this.tableData1 = [];
      },
      initialList() {
          //主表查询
          this.loading = true;
          this.rptTableData = [];
          this.resetData();
          this.$tool
              .request({
                  url: "LIS/LIS5/LIS516",
                  method: "post",
                  data: {
                      action: "query",
                      instrid: this.instrId,
                      selbatch:this.selbatch,
                  },
              })
              .then((res) => {
                  this.tableData1 = res.Data;
                  this.rptTableData = res.RptData;
                  if (this.tableData1.length > 0) {
                      setTimeout(() => {
                          this.$refs.xTable1.setCurrentRow(this.tableData1[0]);
                          this.chkindex();
                      }, 150);
                  }
                  this.loading = false;
              })
              .catch((e) => {
                  this.loading = false;
              });
      },
      cleansel() {
          this.rptTableData.forEach((e) => {
              e.sel = "0";
          });
      },
      chkindex() {
          this.cleansel();
          var currentrow = this.$refs.xTable1.getCurrentRow();
          var rpt_itemcodes = "";
          if (currentrow) rpt_itemcodes = currentrow.rpt_itemcodes;
          if (rpt_itemcodes.length > 0) {
              var tempcodes = "," + rpt_itemcodes + ",";
              this.rptTableData.forEach((e) => {
                  var se = "," + e.rpt_itemcode + ",";
                  if (tempcodes.indexOf(se) > -1) {
                      e.sel = "1";
                  }
              });
              this.rptTableData.sort((a, b) => b.sel - a.sel);
          }
      },
      //切换仪器时刷新界面
      labinstrumentchange(id, name) {
          this.instrId = id;
          this.$nextTick(() => {
              this.initialList();
          });
      },

      BtnAdd() {
          var row = {};
          this.insertRowAtLast(this.$refs.xTable1, row);
          this.cleansel();
      },

      BtnSave() {
          if (this.instrId == 0) {
              this.$message("请选择仪器");
              return false;
          }
          //校验 数据
          var record = this.$refs.xTable1.tableData;
          for (let i = 0, len = record.length; i < len; i++) {
              let msg;
              msg = this.valid(record[i].instrsampleno, "第" + (i + 1) + "行 仪器标本号 必须填写！");
              if (msg) return msg;
              msg = this.valid(record[i].qclevel, "第" + (i + 1) + "行 水平 必须填写！");
              if (msg) return msg;
          }
          let xTable1data = this.$refs.xTable1.getRecordset();
          this.getDataByAjax(
              {
                  url: "LIS/LIS5/LIS516",
                  method: "post",
                  data: {
                      action: "save",
                      instrId: this.instrId,
                      urec: xTable1data,
                  },
              },
              "操作成功！",
              "保存失败！",
              (data) => {
                  //okFunction
                  this.initialList();
              },
              (data) => {
                  //errFunction
              }
          );
      },

      //输入时 itemchanged 事件的例子 ，用了 提示框  this.$confirm
      batchno_changeEvent({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }, inputValue) {
          let batchno = inputValue.target.value;
          if (batchno.trim().length > 0) {
              this.$confirm("只有在 同一天同一个水平要使用多个批号的质控品，这种特殊情况才需要指定批号，否则可能导致下次更换批号后质控结果就无法从仪器接收了。<br/><br/>您还坚持要指定批号吗？", "提示：强烈建议对应批号字段设定为空！", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                  dangerouslyUseHTMLString: true,
              })
                  .then(() => {})
                  .catch((e) => {
                      row.batchno = "";
                  });
          }
      },

      BtnDel() {
          this.deleteRow(this.$refs.xTable1);
      },

      ///////////////////////////////////工具函数 /////////////////////////////////////////
      getDataByAjax(
          request,
          okMsg,
          errMsg,
          okFunction, // 取得数据后的回调函数
          errFunction // 获取数据失败后回调函数
      ) {
          this.$tool.request(request).then((response) => {
              if (response.errcode == "1") {
                  if (XEUtils.isString(okMsg)) {
                      if (XEUtils.getSize(XEUtils.trim(okMsg)) > 0) {
                          this.$message({
                              message: okMsg,
                              type: "success",
                          });
                      }
                  }
                  if (typeof okFunction == "function") okFunction(response.Data);
              } else {
                  this.$message({
                      dangerouslyUseHTMLString: true,
                      message: errMsg + "<br><br>详细信息：" + response.errmsg,
                      type: "warning",
                  });
                  if (typeof errFunction == "function") errFunction(response.Data);
              }
          });
      },

      insertRowAtLast(xtable, row) {
          xtable.insertAt(row, -1); //在最后添加一行
          var curow = xtable.getTableData().fullData[xtable.getTableData().fullData.length - 1]; //获取 新加的行对象 row 数据集合
          xtable.setCurrentRow(curow); //高亮显示行
          this.$nextTick(() => {
              xtable.scrollToRow(curow); //待数据加载完成后，延迟 滚动 到行
          });
      },

      //自动加载表格的第一行，并执行回调函数
      loadFirstRow(xTable, func) {
          this.$nextTick(() => {
              // 加载第一行
              var selectrow = xTable.getData(0);
              if (selectrow) {
                  xTable.setCurrentRow(selectrow); //高亮行
                  xTable.scrollToRow(selectrow); //滚动到行
                  if (typeof func == "function") func(selectrow);
              } else {
                  xTable.setCurrentRow(null); //这个不会自动清空
              }
          });
      },

      //自制必填校验函数，以后待扩展
      valid(obj, message) {
          if (XEUtils.isUndefined(obj)) {
              return this.$message({
                  message: message,
                  type: "warning",
              });
          }
          if (XEUtils.isNull(obj)) {
              return this.$message({
                  message: message,
                  type: "warning",
              });
          }
          if (XEUtils.isString(obj)) {
              if (!XEUtils.getSize(obj) > 0) {
                  return this.$message({
                      message: message,
                      type: "warning",
                  });
              }
          }
          if (XEUtils.isDate(obj)) {
              if (obj < XEUtils.toStringDate("2000-01-01")) {
                  return this.$message({
                      message: message,
                      type: "warning",
                  });
              }
          }
      },

      //删除表格行工具//TODO 连续 点删除按钮会有失去焦点的问题待解决
      deleteRow(xTable) {
          var delrow = xTable.getCurrentRow();
          this.DelIndex = xTable.getRowIndex(delrow);
          xTable.remove(delrow);
          this.cleansel();
          if (this._this.DelIndex > -1 && xTable.tableData.length > 0) {
              if (xTable.getTableData().fullData.length > this.DelIndex) this.DelIndex = this.DelIndex;
              elsethis.DelIndex = this.DelIndex - 1;
              var selectrow = xTable.getTableData().fullData[this._this.DelIndex];
              this.$nextTick(() => {
                  xTable.setCurrentRow(selectrow);
              });
          } else {
              var nowdata = xTable.getTableData().fullData.filter((item) => {
                  return item._XID < delrow._XID;
              });
              if (nowdata.length > 0) {
                  var selectrow = nowdata[nowdata.length - 1];
                  this.$nextTick(() => {
                      xTable.setCurrentRow(selectrow);
                  });
              }
          }
      },

      stddevp(numbers) {
          var mean = 0;
          var sum = 0;
          var avgValue, sdValue, cvValue;
          for (var i = 0; i < numbers.length; i++) {
              sum += Number(numbers[i]);
          }
          mean = sum / numbers.length;
          avgValue = mean;

          sum = 0;
          for (var i = 0; i < numbers.length; i++) {
              sum += Math.pow(numbers[i] - mean, 2);
          }
          sdValue = Math.sqrt(sum / numbers.length);

          if (avgValue != 0) {
              cvValue = (sdValue * 100) / avgValue;
          } else {
              cvValue = null;
          }
          return {
              avgValue: XEUtils.toFixedString(mean, 2),
              sdValue: XEUtils.toFixedString(sdValue, 2),
              cvValue: XEUtils.toFixedString(cvValue, 2),
          };
      },
      //关闭按钮
      BtnExc() {
          let index = this.$parent.$refs.itemtags.tagsList.findIndex((m) => m.name == "LIS516");
          this.$parent.$refs.itemtags.tagsList.splice(index, 1);
          this.$router.go(-1);
      },
  },
  beforeRouteEnter(to, from, next) {
      next((vm) => {
          let that = vm;
          let altArr = [];
          document.onkeydown = function (e) {
              let key = window.event.keyCode;
              //*组合按键
              if (altArr.length > 0) {
                  //65到90 a到z（A到Z）
                  // //*Alt + C 清除
                  // if (key == 67) {
                  //     this.BtnExc();
                  // }
                  //*Alt + E 退出
                  if (key == 69) {
                      that.BtnExc();
                  }
              } else {
                  if (key == 119) {
                      //F8
                      that.initialList();
                  } else if (key == 113) {
                      //F2
                      var e = [];
                      e.shiftKey = false;
                      that.BtnAdd(e);
                  } else if (key == 114) {
                      //F3
                      that.BtnDel();
                  } else if (key == 117) {
                      //F6
                      that.BtnSave();
                  } else if (key == 18) {
                      //按下了alt
                      altArr.push(key);
                  }
              }
          };
          document.onkeyup = function (e) {
              let key = window.event.keyCode;
              if (key == 18) {
                  altArr = [];
              }
          };
      });
  },
};
</script>

<style scoped>
.pagetop {
  left: 0;
  right: 0;
  height: 30px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: solid 1px #ccc;
  position: absolute;
  z-index: 99;
  text-align: left;
}
.pagebottom {
  width: 100%;
  height: 40px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: left;
  position: absolute;
  bottom: 0px;
  font-size: 12px;
  border: solid 1px #ccc;
}
.pagecenter {
  position: absolute;
  top: 35px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}
.middle-center {
  position: absolute;
  height: 100%;
  right: 485px;
  left: 0;
}

.middle-right {
  position: absolute;
  top: 0;
  bottom: 2px;
  overflow: visible;
  width: 480px;
  right: 0px;
}
table tr td:nth-child(odd) {
  text-align: right;
  white-space: nowrap;
}
table tr td:nth-child(even) {
  text-align: left;
}
table tr td:nth-child(1) {
  width: 80px;
}
table {
  font-size: 12px;
}
.datacenter {
  position: absolute;
  top: 30px;
  width: 100%;
  left: 0;
  bottom: 5px;
}
.tab-title {
  margin: 0;
  font-size: 13px;
  /* margin: 0 1px 0 3px; */
  padding: 0 1px 0 3px;
  font-weight: 600;
  width: 100%;
  text-align: left;
  white-space: nowrap;
}
.tabtop {
  width: 100%;
  height: 26px;
  line-height: 26px;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  white-space: nowrap;
}
::v-deep.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  border-color: #000000;
}
</style>
